package com.et114.modules.myet.action;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.et114.core.common.AppContext;
import com.et114.core.utility.FileUtils;
import com.et114.modules.cust.BIZ;
import com.et114.modules.cust.services.IMng_CustService;
import com.et114.modules.cust.services.Mng_CustServiceImp;
import com.et114.modules.cust.vo.CustBaseVo;
import com.et114.modules.cust.vo.CustInfoVo;
import com.et114.modules.myet.dao.IMyEt_UCenterDao;
import com.et114.modules.myet.dao.MyEt_UCenterDaoImp;
import com.et114.modules.myet.form.EtCarFrom;
import com.et114.modules.myet.service.IMyEt_UCenterService;
import com.et114.modules.myet.service.MyEt_UCenterServiceImp;
import com.et114.modules.myet.vo.MyEtOrder_VO;
import com.et114.modules.order.vo.OrderTrack;
import com.et114.modules.order.vo.ProVO;

/**
 * 购物车
 * @author zhiweip
 * @version 1.0
 * @created 22-十二月-2010 13:33:57
 */
public class Et_ShopBagAction extends MyEtAction {
	
	private IMyEt_UCenterDao		m_IMyEt_UCenterDao		= ( MyEt_UCenterDaoImp ) getBean ( "m_IMyEt_UCenterDao" );
	private IMyEt_UCenterService	m_IMyEt_UCenterService	= ( MyEt_UCenterServiceImp ) getBean ( "m_IMyEt_UCenterService" );
	private String					opFlag;
	private String					COUNTRY_ZH;
	
	public void finalize ( ) throws Throwable {
		
	}
	
	/**
	 * ajax 购物车查询
	 */
	public ActionForward unspecified ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {		
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		
		EtCarFrom cForm = ( EtCarFrom ) form;
		
		MyEtOrder_VO shop = new MyEtOrder_VO ( );
		
		try { 
			 
			COUNTRY_ZH = super.getSessionLanguage ( request );
			HashMap optMap=sessionShoppingCar(null,null,request);
			JSONArray comjson = JSONArray.fromObject ( optMap );
			
			String result = comjson.toString ( ); 
			logger.debug ( "========================key=:" + result );
			
			response.getWriter ( ).print ( result );
		} catch ( Exception e ) {
			response.getWriter ( ).print ( e.getMessage ( ) );
			e.printStackTrace ( );
		}
		response.getWriter ( ).flush ( );
		response.getWriter ( ).close ( );
		return null;
	}
	

	
	/**
	 * ajax购物车添加
	 */
	public ActionForward add ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {		
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		EtCarFrom cForm = ( EtCarFrom ) form;
		
		String userid=null;
		 
		
		try {
			String itemtype = request.getParameter ( "itemtype" );
			String itemid = request.getParameter ( "proid" );
			String supid = request.getParameter ( "proSupplierId" );
			String serpid = request.getParameter ( "proServiceId" );
			String color = request.getParameter ( "color" );
			String colorname= request.getParameter ( "colorName" );
			String tempKey = request.getParameter ( "tempKey" );
			if(colorname!=null)
				colorname=new String(colorname.getBytes("ISO8859-1"),"UTF-8");
			
			MyEtOrder_VO shop = new MyEtOrder_VO ( );
			shop.setItemid ( new Integer(itemid) );
			shop.setUnitprice ( new Double ( 0 ) );			
			shop.setItemtype ( itemtype );
			shop.setSerpid ( serpid );
			shop.setSupid ( supid ) ;
			shop.setItemkindID ( color );
			shop.setItemkind ( colorname );
			shop.setSalenum ( 1 ); 	
			if(null == tempKey){
				tempKey="";
			}
			shop.setTempKey ( tempKey );
			
			String result ="";
			COUNTRY_ZH = super.getSessionLanguage ( request );
			HashMap glist =sessionShoppingCar(null,null, request);
			if(glist==null||glist.size ( )<11){
				glist =sessionShoppingCar("add",shop, request);
				JSONArray comjson = JSONArray.fromObject ( glist );
				result = comjson.toString ( );
			}else{
				Map rmap=new HashMap();
				rmap.put ( "opResult" , "max" );
				JSONArray comjson = JSONArray.fromObject ( rmap );
				result = comjson.toString ( );
			}
			
			logger.debug ("========================key=:" + result );
			response.getWriter ( ).print ( result );
		} catch ( Exception e ) {
			response.getWriter ( ).print ( e.getMessage ( ) );
			e.printStackTrace ( );
		}
		response.getWriter ( ).flush ( );
		response.getWriter ( ).close ( );
		return null;
	}
	
	/**
	 * ajax 购物车修改
	 */
	public ActionForward del ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {		
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		EtCarFrom cForm = ( EtCarFrom ) form;	
		
		try {
			String itemtype = request.getParameter ( "itemtype" );
			String itemid = request.getParameter ( "proid" );
			String supid = request.getParameter ( "proSupplierId" );
			String serpid = request.getParameter ( "proServiceId" );
			String color = request.getParameter ( "color" );
			String colorname= request.getParameter ( "colorName" );
			String tempKey = request.getParameter ( "tempKey" );
			if(colorname!=null)
				colorname=new String(colorname.getBytes("ISO8859-1"),"UTF-8");
			
			MyEtOrder_VO shop = new MyEtOrder_VO ( );
			shop.setItemid ( new Integer(itemid) );
			shop.setUnitprice ( new Double ( 0 ) );			
			shop.setItemtype ( itemtype );
			shop.setSerpid ( serpid );
			shop.setSupid ( supid ) ;
			shop.setItemkindID ( color );
			shop.setItemkind ( colorname );
			shop.setSalenum ( 1 );
			if(null == tempKey){
				tempKey="";
			}
			shop.setTempKey ( tempKey );
			
			HashMap list=sessionShoppingCar("del",shop,request);	
			JSONArray comjson = JSONArray.fromObject ( list );
			String result = comjson.toString ( );
			logger.debug ("========================key=:" + result );
			response.getWriter ( ).print ( result );
		} catch ( Exception e ) {
			response.getWriter ( ).print ( e.getMessage ( ) );
			e.printStackTrace ( );
		}
		response.getWriter ( ).flush ( );
		response.getWriter ( ).close ( );
		return null;
	}
	
	public ActionForward modify ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {		
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		EtCarFrom cForm = ( EtCarFrom ) form;	
		
		try {
			String itemtype = request.getParameter ( "itemtype" );
			String itemid = request.getParameter ( "proid" );
			String supid = request.getParameter ( "proSupplierId" );
			String serpid = request.getParameter ( "proServiceId" );
			String color = request.getParameter ( "color" );
			String buynum = request.getParameter ( "buynum" );
			String tempKey = request.getParameter ( "tempKey" );
			
			MyEtOrder_VO shop = new MyEtOrder_VO ( );
			shop.setItemid ( new Integer(itemid) );
			shop.setUnitprice ( new Double ( 0 ) );			
			shop.setItemtype ( itemtype );
			shop.setSerpid ( serpid );
			shop.setSupid ( supid ) ;
			shop.setItemkindID ( color );
			if(null == tempKey){
				tempKey="";
			}
			shop.setTempKey ( tempKey );
			try {
				shop.setSalenum ( buynum==null?0:new Integer(buynum) );
			} catch ( Exception e ) { return null; } 
			
			
			HashMap list=sessionShoppingCar("upd",shop,request);	
			JSONArray comjson = JSONArray.fromObject ( list );
			String result = comjson.toString ( );
			logger.debug ("========================key=:" + result );
			response.getWriter ( ).print ( result );
		} catch ( Exception e ) {
			response.getWriter ( ).print ( e.getMessage ( ) );
			e.printStackTrace ( );
		}
		response.getWriter ( ).flush ( );
		response.getWriter ( ).close ( );
		return null;
	}
	
	/**
	 * 购物车查询
	 */
	public ActionForward carList ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		ClassLoader loader=this.clazz.getClassLoader();   
 
		String path=loader.getResource ( "" ).getPath ( );
		int e=loader.getResource ( "" ).getPath ( ).indexOf ( "WEB-INF" );
		//System.out.println ("=============="+path.substring ( 1,e-1 ));
		MyEtOrder_VO shop = new MyEtOrder_VO ( );
		
		request.setAttribute ( "BuyList" , sessionShoppingCar(null,null,request));
		request.setAttribute ( "noLogin" , "noLogin" );
		
		return mapping.findForward ( "shopcar" );
	}
	
	
	/**
	 * 结算确认
	 */
	public ActionForward confirm ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		if ( isNeedLogin ( request ,"Et_ShopBagAction.go?method=carList") ) {  
			response.sendRedirect ( "login.html" ); return mapping.findForward ( "" );}
		
		try{
			
		IMng_CustService mng_CustService = ( Mng_CustServiceImp ) getBean ( "mng_CustService" );
		
		CustBaseVo cust = new CustBaseVo ( );
		cust.setCustid (   super.getCustId ( request ) ); 
		cust = mng_CustService.loadCust ( cust );
		//客户信息是否完备
		if ( cust==null||cust.getMobileno ( ) == null || cust.getMobileno ( ).equals ( "" )
				|| cust.getSafeno ( ) == null
				|| cust.getSafeno ( ).equals ( "" )
				|| cust.getFamname ( ).equals ( "" )
				|| cust.getFamname ( ).equals ( "" )
				|| cust.getCustname ( ) == null
				|| cust.getCustname ( ).equals ( "" )
				|| cust.getBirth ( ) == null || cust.getBirth ( ).equals ( "" ) ) {
			request.setAttribute ( "OPFLAG" , "deny" );
		}
		EtCarFrom cForm = ( EtCarFrom ) form;
		
		
		String [] shcarid = request.getParameterValues ( "shcarid" );
		
		if(shcarid==null || shcarid.length<=0){
			request.setAttribute ( "result" , "error" );
			return mapping.findForward ( "et_info" );
		}
		
		COUNTRY_ZH = super.getSessionLanguage ( request ); 
		
		List < MyEtOrder_VO > list = loadSelectedDetail ( request , shcarid );
		if(list.size ( )<=0) {
			request.setAttribute ( "result" , "error" );
			return mapping.findForward ( "et_info" );
		}
		 
		logger.debug ("----------------shcarid.length: "+list.size ( ));
		request.setAttribute ( "BuyList" , list );
		
		
		CustInfoVo info = new CustInfoVo ( );
		info.setCustid ( getCustId ( request ) );
		info.setDtype ( BIZ.CUST_DTYPE_LINK );
		request.setAttribute ( "LgiList" , mng_CustService
				.loadCustMsgByType ( info ) );
		
		info.setDtype ( BIZ.CUST_DTYPE_BILL );
		request.setAttribute ( "BillList" , mng_CustService
				.loadCustMsgByType ( info ) );
		
		info.setDtype ( BIZ.CUST_DTYPE_CRET );
		request.setAttribute ( "CretList" , mng_CustService
				.loadCustMsgByType ( info ) );
		
		info.setDtype ( BIZ.CUST_DTYPE_LIC );
		request.setAttribute ( "LicList" , mng_CustService
				.loadCustMsgByType ( info ) );
		}catch(Exception e){
			e.printStackTrace ( );
		}
		
		
		return mapping.findForward ( "confirm" );
	}

	
	/**
	 * 生成订单
	 */
	public ActionForward save ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		if ( isNeedLogin ( request ) ) {  response.sendRedirect ( "login.html" );return mapping.findForward ( "" ); }
		
		COUNTRY_ZH = super.getSessionLanguage ( request );
		 
		
		
		EtCarFrom cForm = ( EtCarFrom ) form;
		cForm.setCustid ( getCustId ( request ) );
		cForm.setUserid ( getUserId ( request ) );
		cForm.setCountry_ZH ( COUNTRY_ZH );
		
		String [] shcarid = request.getParameterValues ( "shcarid" );
		List < MyEtOrder_VO > list = loadSelectedDetail ( request , shcarid );
		if(list==null || list.size ( )<=0) {
			request.setAttribute ( "result" , "error" );
			return mapping.findForward ( "et_info" );
		} 
		
		if(shcarid==null || shcarid.length<=0){
			request.setAttribute ( "result" , "error" );
			request.setAttribute ( "errormsg" , "购物车空!" );
			return mapping.findForward ( "et_info" );
		}
		
		for(MyEtOrder_VO cc:list){
			if(!"2".equals ( cc.getOperType ( ))){//是否已下架?
				request.setAttribute ( "result" , "proout" );
				request.setAttribute ( "msg" , "\""+cc.getItemtitle ( ) +"\"");
				request.setAttribute ( "back" , "Et_ShopBagAction.go?method=carList" );
				sessionShoppingCar("del",cc,request);
				return mapping.findForward ( "et_info" );
			} 
			
		}
		
		m_IMyEt_UCenterService.insertOrder ( request , cForm ,list);
		
		for(MyEtOrder_VO et:list){
			sessionShoppingCar("del",et,request);
		}
		
		request.setAttribute ( "result" , "orderok" );
		request.setAttribute ( "back" , "MyEt_orderAction.go" );
		return mapping.findForward ("et_info_ord");
	}
	
	/**
	 * 缓存中的购物车
	 * @throws Exception 
	 */
	private HashMap sessionShoppingCar(String opflag,MyEtOrder_VO et,HttpServletRequest request) throws Exception{  
		
		HttpSession session = request.getSession ( ); 
		
		Object opt = session.getAttribute ( BIZ.SESSIOIN_SHOPINGCAR );
		HashMap<String,List> optMap=(HashMap)opt;
		//optMap=new HashMap < String , List >();
		//session.setAttribute ( BIZ.SESSIOIN_SHOPINGCAR ,optMap);
		if(optMap == null){
			optMap=new HashMap ();
		}
		
		String key = "";
		if(et!=null){
			key = "Map_"+et.getItemtype ( ) + "_" + et.getSupid ( )+"_key";
		}
		logger.debug ("=====SESSIOIN_SHOPINGCAR==============="+key);
		if ( et!=null && opflag!=null && opflag.equals ( "del" ) ) { 
			key+=et.getTempKey ( );
			//System.out.println ("=====del=========:"+key);
			List < MyEtOrder_VO > ssList = optMap.get ( key );
			if(ssList!=null)
			for ( MyEtOrder_VO ord : ssList ) {
				if ( compareToShop ( ord , et ) ) {
					ssList.remove ( ord );
					break;
				}
			}
			optMap.put ( key , ssList ); 
			ssList = optMap.get ( key );
			if(ssList==null||ssList.size ( )<=0){
				optMap.remove ( key );
				//System.out.println ("========deelet:  "+key+"optMap.get ( key ):"+optMap.get ( key ));
			}
			session.setAttribute ( BIZ.SESSIOIN_SHOPINGCAR ,optMap);
			
		}else if( et!=null && opflag!=null && opflag.equals ( "add")){			
			boolean isFind=false;
			String tempKey="";
			if(BIZ.TYPES_SAFE.equals ( et.getItemtype ( ) )||BIZ.TYPES_TV.equals ( et.getItemtype ( ) )){
				tempKey=String.valueOf ( System.currentTimeMillis ( ) );
			}
			key+=tempKey;
			//System.out.println ("key+=tempKey===="+key);
			
			List<MyEtOrder_VO> ssList=optMap.get ( key );
			if(ssList==null){
				ssList=new ArrayList < MyEtOrder_VO >();
				MyEtOrder_VO ord=getDetail(et);
				if(ord!=null){
					//System.out.println ("=====dd=========:"+tempKey);
					ord.setTempKey ( tempKey );
					ssList.add ( ord );
				}
			}else{ 
				for ( MyEtOrder_VO ord : ssList ) {				
					if (compareToShop(ord,et)) {
							isFind=true;
							ord.setSalenum ( ord.getSalenum ( ).intValue ( )+1 );
							break;
					}
				}
				if(!isFind){
					try {
						MyEtOrder_VO ord=getDetail(et);
						if(ord!=null){
							//System.out.println ("=====bb=========:"+tempKey);
							ord.setTempKey ( tempKey );
							ssList.add ( ord );
						}
					} catch ( Exception e ) { 
						e.printStackTrace();
					}
				}
			}
			optMap.put ( key , ssList );
			session.setAttribute ( BIZ.SESSIOIN_SHOPINGCAR ,optMap);
			
		} else if (  et!=null && opflag != null && opflag.equals ( "upd" ) ) {
			
			List < MyEtOrder_VO > ssList = optMap.get ( key );
			if(ssList!=null)
				for ( MyEtOrder_VO ord : ssList ) {
					if ( compareToShop ( ord , et ) ) {
						ord.setSalenum ( et.getSalenum ( ) );
						break;
					}
				} 
			optMap.put ( key , ssList );
			//optMap=new HashMap ();
			session.setAttribute ( BIZ.SESSIOIN_SHOPINGCAR ,optMap);
			return optMap;

		}
		opt = session.getAttribute ( BIZ.SESSIOIN_SHOPINGCAR );
		optMap=(HashMap)opt;
		if(optMap == null){
			optMap=new HashMap ();
		} 
		return optMap;
		
	}
	
	
	
	private MyEtOrder_VO getSessionShoppingCar(MyEtOrder_VO et,HttpServletRequest request) throws Exception{ 
		String key = "";
		if(et!=null){
		 key = "Map_"+et.getItemtype ( ) + "_" + et.getSupid ( )+"_key"+et.getTempKey ( ); 
		}
		HttpSession session = request.getSession ( );
		Object opt = session.getAttribute ( BIZ.SESSIOIN_SHOPINGCAR );
		HashMap<String,List> optMap=(HashMap)opt;
		List < MyEtOrder_VO > ssList = optMap.get ( key );
		if(ssList!=null&&ssList.size ( )>0){
			for ( MyEtOrder_VO ord : ssList ) {
				if ( compareToShop ( ord , et ) ) {
					return ord;
				}
			}
		}
		return null;
	}
	
	private boolean compareToShop ( MyEtOrder_VO ord , MyEtOrder_VO dis ) {
		logger.debug ("||"+ord.getItemid ( )+"|"+ord.getItemkindID ( )+"|"+ord.getSerpid ( ));
		logger.debug ("//"+dis.getItemid ( ) +"|"+dis.getItemkindID ( )+"|"+dis.getSerpid ( ));
		if ( ord == null || dis == null )
			return false;
		
		if ( ord.getItemtype ( ).equals ( BIZ.TYPES_PC )
				|| ord.getItemtype ( ).equals ( BIZ.TYPES_TEL ) ) {
			
			if ( ord.getItemid ( ).compareTo ( dis.getItemid ( ) ) == 0
					&& ord.getItemkindID ( ).equals ( dis.getItemkindID ( ) )
					&& ord.getSerpid ( ).equals ( dis.getSerpid ( ) )
					&& ord.getItemtype ( ).equals ( dis.getItemtype ( ) ) ) {
				return true;
			} else {
				return false;
			}
		} else {
			if ( ord.getItemid ( ).compareTo ( dis.getItemid ( ) ) == 0
					&& ord.getItemtype ( ).equals ( dis.getItemtype ( ) ) ) {
				return true;
			} else {
				return false;
			}
		}
	}
	/**
	 * 封装单个商品详细信息
	 */
	private MyEtOrder_VO getDetail ( MyEtOrder_VO et) throws Exception {
		if(et==null) return null;
			et.setCountry_ZH ( COUNTRY_ZH );
			String itemtype = et.getItemtype ( );
			ProVO detail = new ProVO ( );
			if ( itemtype.equals ( BIZ.TYPES_CERT ) ) {
				detail = m_IMyEt_UCenterService.getDetailCard ( et , null );
				
			} else if ( itemtype.equals ( BIZ.TYPES_PC ) ) {
				detail = m_IMyEt_UCenterService.getDetailPc ( et , null );
				
			} else if ( itemtype.equals ( BIZ.TYPES_SAFE ) ) {
				detail = m_IMyEt_UCenterService.getDetailSafe ( et , null );
				
			} else if ( itemtype.equals ( BIZ.TYPES_TEL ) ) {
				detail = m_IMyEt_UCenterService.getDetailTel ( et , null );
				
			} else if ( itemtype.equals ( BIZ.TYPES_TV ) ) {
				detail = m_IMyEt_UCenterService.getDetailTV ( et , null );
				
			}
			if(detail==null) return null;
			
			PropertyUtils.copyProperties ( et , detail );
		return et;
	}
	
	private String copySaveImg ( MyEtOrder_VO et ) {
		String newItemimgname="/views/et114-img/S";
		try{
			String newpath="";
			ClassLoader loader=super.getClass ( ).getClassLoader ( );  
			String path=loader.getResource ( "" ).getPath ( );
			
			int e=loader.getResource ( "" ).getPath ( ).indexOf ( "WEB-INF" );
			path=path.substring ( 1,e-1 );
			//System.out.println ("==============path= "+path);
			
			File oldfile=new File(path+et.getItemimg ( ));
			//System.out.println ("============="+path+et.getItemimg ( ));
			FileUtils.copy2 ( oldfile,path+newItemimgname, false );
			return newItemimgname;
		}catch(Exception e){
			e.printStackTrace ( );
		}
		newItemimgname=et.getItemimg ( );
		return newItemimgname;
	}
	
	
	private List < MyEtOrder_VO > loadSelectedDetail (
			HttpServletRequest request , String [ ] shcarid ) throws Exception {
		if(shcarid==null) return null;
		List < MyEtOrder_VO > list=new ArrayList < MyEtOrder_VO >();
		MyEtOrder_VO shop = null; 
		for(String keyid:shcarid){
			shop = new MyEtOrder_VO ( ); 
			//${card.itemtype}|${card.supid}|${card.serpid}|${card.itemkindID}|${card.itemid}
			logger.debug ("--------------------keyid:"+keyid);
			String[] key=keyid.split ( ";" ); 
			//System.out.println ("--------------------keyid:"+key[0]+" key[1]:"+key[1]+" key[2]:"+key[2]+" key[3]:"+key[3]+" key[4]:"+key[4]+" key[5]:"+key[5]);
			shop.setItemtype ( key[0] );
			shop.setSupid ( key[1] );
			shop.setSerpid ( key[2] );
			shop.setItemkindID ( key[3] );
			shop.setItemid ( new Integer(key[4]) );
			shop.setTempKey ( key[5] );
			shop=getSessionShoppingCar(shop,request);
			shop=getDetail ( shop );
			if(shop!=null){
				shop.setTempKey ( key[5] );
				list.add ( shop );
			}
		}
		return list;
	}
	
}